package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"github.com/apache/rocketmq-client-go/v2/primitive"

	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/producer"
)

type OrderListener struct{}

func (OrderListener) ExecuteLocalTransaction(*primitive.Message) primitive.LocalTransactionState {
	fmt.Println("开始执行本地逻辑")
	time.Sleep(time.Second * 3)
	fmt.Println("执行本地逻辑完成")
	return primitive.UnknowState
}

func (OrderListener) CheckLocalTransaction(*primitive.MessageExt) primitive.LocalTransactionState {
	fmt.Println("开始回查本地逻辑")
	time.Sleep(time.Second * 3)
	fmt.Println("回查成功, 开始投递")
	return primitive.CommitMessageState
}

func main() {
	p, _ := rocketmq.NewTransactionProducer(
		&OrderListener{},
		producer.WithNameServer([]string{"120.24.67.46:9876"}),
	)
	err := p.Start()

	if err != nil {
		fmt.Printf("生成producer失败: %s", err.Error())
		os.Exit(1)
	}

	res, err := p.SendMessageInTransaction(context.Background(), primitive.NewMessage("transaction_message", []byte("这是一条事务消息55555")))
	if err != nil {
		fmt.Printf("发送失败 : %s\n", err)
	} else {
		fmt.Printf("发送成功: result=%s\n", res.String())
	}

	time.Sleep(time.Hour) // 用于执行事务回查

	err = p.Shutdown()
	if err != nil {
		fmt.Printf("shutdown producer error: %s", err.Error())
	}
}
